package com.scau.XFourPOS.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.mapping.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionContext;
import com.scau.XFourPOS.model.Customer;
import com.scau.XFourPOS.model.Product;
import com.scau.XFourPOS.model.SaleOrder;
import com.scau.XFourPOS.model.SaleOrderItem;
import com.scau.XFourPOS.service.CustomerService;
import com.scau.XFourPOS.service.ProductService;
import com.scau.XFourPOS.service.SaleOrderItemService;
import com.scau.XFourPOS.service.SaleOrderService;
import com.scau.XFourPOS.utils.PageUtils;

@Controller
@ParentPackage("struts-default")
public class SaleOrderAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	@Autowired
	private ProductService productService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private SaleOrderItemService saleOrderItemService;
	@Autowired
	private SaleOrderService saleOrderService;
	private String code;
	private int amount;
	private String phone;
	private String customerId;
	private String total;
	private String data;
	private String key;
	private String saleOrderNO;

	/**
	 * 添加一行购物车商品列表
	 */
	@Action("productLoadByCodeAction")
	public void loadByCode() {
		Json result = new Json();
		if (productService.isExitEntity("code", code)) {
			try {
				Product product = productService.loadByCode(code);
				product.setAmount(amount);
				result.setObj(product);
				result.setSuccess(true);
				result.setMsg("添加商品列表成功");
			} catch (Exception e) {
				result.setMsg("添加列表产品失败");
			}
		} else {
			result.setSuccess(false);
			result.setMsg("该商品不存在");
		}
		writeJson(result);
	}

	/**
	 * 验证用户是否存在-创建订单
	 */
	@Action("CustomerIsExitAction")
	public void CustomerIsExitAction() {
		Json result = new Json();
		if (customerService.isExitEntity(key, phone)) {
			SaleOrder saleOrder = new SaleOrder();
			saleOrder.setCustomer(customerService.loadEntityByKey(key, phone));
			saleOrder.setTotal(Double.parseDouble(total));
			saleOrderService.saveEntity(saleOrder);
			ActionContext actionContext = ActionContext.getContext();
			actionContext.getSession().put("saleOrderNO",saleOrder.getSaleOrderNO());
			saleOrder.getSaleOrderNO();
			result.setSuccess(true);
			result.setMsg("用户信息正确");
		} else {
			result.setSuccess(false);
			result.setMsg("不存在该用户");
		}
		writeJson(result);
	}

	/**
	 * 获得产品列表数据，创建并提交返回订单
	 */
	@Action("SaleOrderAddAction")
	public void addSaleOrder() {
		Json result = new Json();
		JSONObject json = JSON.parseObject(data);// 把穿过来的data值转化为json
		int num = Integer.parseInt(json.get("total").toString());// 获取总行数
		List<Object> message = (List<Object>) json.get("rows");// 解析信息内容为list
		JSONArray messageArray = new JSONArray(message);// 把list转化为jsonarray
		if (num==0) {
			result.setMsg("商品列表为空");
			result.setSuccess(false);
		} else {
			result.setMsg("提交订单成功");
			result.setSuccess(true);
			ActionContext actionContext = ActionContext.getContext();
			String saleOrderNO=actionContext.getSession().get("saleOrderNO").toString();
			SaleOrder saleOrder=saleOrderService.loadEntityByKey("saleOrderNO", saleOrderNO);
			for (int i = 0; i < num; i++) {
				SaleOrderItem saleOrderItem=new SaleOrderItem();
				saleOrderItem.setPrice(Double.parseDouble(messageArray.getJSONObject(i).get("price").toString()));
				Product product=productService.loadEntityByKey("code",messageArray.getJSONObject(i).get("code").toString());
				saleOrderItem.setProduct(product);
				saleOrderItem.setQuanity(Integer.parseInt( messageArray.getJSONObject(i).get("amount").toString()));
				saleOrderItem.setSaleOrder(saleOrder);
				saleOrderItemService.saveEntity(saleOrderItem);
			}
			result.setObj(saleOrderNO);
		}
		writeJson(result);
	}
	
	/**
	 * 订单退货处理，显示订单详情
	 */
	@Action("saleOrderLoadItemAction")
	public void saleOrderReturn() {
		Json result = new Json();
		if (saleOrderService.isExitEntity("saleOrderNO", saleOrderNO)) {
			PageUtils<SaleOrderItem> pageUtils = new PageUtils<SaleOrderItem>(page, rows,
					sort, order);
			int id=saleOrderService.loadEntityByKey("saleOrderNO", saleOrderNO).getId();
			List<SaleOrderItem> list = saleOrderItemService.loadByPageAndKey(pageUtils, "saleOrder", id).getResult();
			ArrayList datas = new ArrayList();//封装JOSN串
			for(int i = 0 ;i<list.size();i++){
				SaleOrderItem item = list.get(i);
				HashMap map = new HashMap();
				map.put("itemId", item.getId());
				map.put("productId", item.getProduct().getProductId());
				map.put("code",item.getProduct().getCode());
				map.put("name",item.getProduct().getName());
				map.put("description",item.getProduct().getDescription());
				map.put("price", item.getProduct().getPrice());
				map.put("quanity",item.getQuanity());
				map.put("total",item.getPrice());
				datas.add(map);
			}
			long total = pageUtils.getTotalCount();
			writeJson(total, datas);

		} else {
			result.setSuccess(false);
			result.setMsg("该订单号码不存在");
			writeJson(result);
		}
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public String getTotal() {
		return total;
	}

	public void setTotal(String total) {
		this.total = total;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public int getAmount() {
		return amount;
	}

	public void setAmount(int amount) {
		this.amount = amount;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getSaleOrderNO() {
		return saleOrderNO;
	}

	public void setSaleOrderNO(String saleOrderNO) {
		this.saleOrderNO = saleOrderNO;
	}

}
